﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Physis.Security {

    public class RolePermission : Core.CoreObject {
        
        #region Private Properties

        private Int64 roleId = 0;

        private Int64 permissionId = 0;

        private Boolean granted = false;

        private Boolean denied = false;


        private Permission permission = null;

        #endregion 


        #region Public Properties

        public override String Name {

            get {

                if (permission == null) { permission = Application.Security.Permission (permissionId, true); }

                return ((permission != null) ? permission.Name : String.Empty);

            }

        }

        public override String Description {

            get {

                if (permission == null) { permission = Application.Security.Permission (permissionId, true); }

                return ((permission != null) ? permission.Description : String.Empty);

            }

        }


        public Int64 RoleId { get { return roleId; } set { roleId = value; } }

        public Int64 PermissionId { get { return permissionId; } set { permissionId = value; } }

        public Boolean Granted { get { return granted; } set { granted = value; } }

        public Boolean Denied { get { return denied; } set { denied = value; } }


        public Permission Permission {

            get {

                if (permission == null) { permission = Application.Security.Permission (permissionId, true); }

                return permission;

            }

        }

        #endregion 

        
        #region Constructors

        public RolePermission () { /* DO NOTHING, FOR JSON DESERIALIZATION ONLY */ }

        public RolePermission (Application forApplication) : base (forApplication) {

            return;

        }

        public RolePermission (Application forApplication, Int64 forId) : base (forApplication) {

            if (!Load (forId, Application.EnterpriseDatabase)) {

                throw new Exception (GetType ().FullName + ".Load [Failed]: " + forId);

            }

            return;

        }

        #endregion


        #region Database Functions 

        protected override Dictionary<string, string> Validate () {

            // VALIDATE THAT THE ROLE AND PERMISSION ARE GOOD, SINCE THE OWNING ROLE COULD BE BRAND NEW AND IN A TRANSACTION, WE NEED TO JUST CHECK LOCAL 

            // DO NOT CALL THE BASE VALIDATIONS SINCE NAME/DESCRIPTION ARE NOT REQUIRED 

            Dictionary<String, String> validationErrors = new Dictionary<String, String> ();
            
            if (roleId == 0) { validationErrors.Add ("Role", "Role Reference is empty or null."); }

            if (permissionId == 0) { validationErrors.Add ("Permission", "Permission Reference is empty or null."); }

            return validationErrors;

        }

        public override void MapDataFields (System.Data.DataRow currentRow) {

            base.MapDataFields (currentRow);

            roleId = Data.Readers.DataReader.Int64FromDatabase (currentRow, "RoleId");

            permissionId = Data.Readers.DataReader.Int64FromDatabase (currentRow, "PermissionId");

            granted = Data.Readers.DataReader.BooleanFromDatabase (currentRow, "Granted");

            denied = Data.Readers.DataReader.BooleanFromDatabase (currentRow, "Denied");

            return;

        }

        public override Boolean Save () {

            Boolean success = false;

            try {

                Dictionary<String, String> validationErrors = Validate ();

                if (validationErrors.Count > 0) {

                    Application.SetLastException (new Exception ("Invalid [" + validationErrors.Keys.First () + "]: " + validationErrors.Values.First ()));

                    return false;

                }

                UpdateModifiedToSessionUser ();

                
                System.Data.IDbCommand command = Application.EnterpriseDatabase.CreateCommand (ObjectType + "_InsertUpdate");

                command.CommandType = System.Data.CommandType.StoredProcedure;


                Application.EnterpriseDatabase.AppendCommandParameter (command, "RoleId", RoleId);

                Application.EnterpriseDatabase.AppendCommandParameter (command, "PermissionId", PermissionId);

                Application.EnterpriseDatabase.AppendCommandParameter (command, "Granted", Granted);

                Application.EnterpriseDatabase.AppendCommandParameter (command, "Denied", Denied);

                Application.EnterpriseDatabase.AppendCommandParameter (command, "ModifiedId", Application.Session.UserAccountName, 60);

                success = (command.ExecuteNonQuery () > 0);

                if (success) { SetIdentity (Application.EnterpriseDatabase); }

            }

            catch (Exception exception) {

                success = false;

                Application.SetLastException (exception);

            }

            return success;

        }

        #endregion 

    }
}
